<template>
  <div class="app-container">
    <!-- <el-card> -->
    <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
      <el-tab-pane label="全部" name="1">
        <el-table
          ref="jobFairTable"
          :data="selJobFairLists"
          style="width: 100%"
          sortable
          @selection-change="handleSelectionJobFireChange"
        >
          <!-- <el-table-column
            type="selection"
            width="55"
            :selectable="checkSelectable"
          >
          </el-table-column> -->
          <el-table-column prop="prop" label="招聘会内容" width="500">
            <template slot-scope="scope">
              <h3>{{ scope.row.title }}</h3>
              <div>
                报名时间：{{ scope.row.signStartTime | dateFormat }} 至
                {{ scope.row.signEndTime | dateFormat }}
              </div>
              <div>
                举办时间：{{ scope.row.holdStartTime | dateFormat }} 至
                {{ scope.row.holdEndTime | dateFormat }}
              </div>
              <div>
                参会企业{{ scope.row.totalCompany }} 参会个人{{
                  scope.row.totalPersonal
                }}
                浏览次数 {{ scope.row.click }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="type"
            label="类型"
            width="width"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.type === 1 ? "线上" : "线下" }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="address" label="地址">
          </el-table-column>
          <el-table-column
            align="center"
            prop="prop"
            label="参会状态"
            width="width"
          >
            <template slot-scope="scope">
              <el-tag
                v-if="scope.row.companyStatus === 0"
                type="info"
                size="medium"
              >
                未参加
              </el-tag>
              <el-tag
                v-if="scope.row.companyStatus === 1"
                type="warning"
                size="medium"
              >
                已报名
              </el-tag>
              <el-tag
                v-if="scope.row.companyStatus === 2"
                type="success"
                size="medium"
              >
                已参加
              </el-tag>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" prop="prop" label="是否参加招聘会">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="small"
                  v-if="
                    scope.row.companyStatus === 0 &&
                    new Date() <= new Date(scope.row.signStartTime * 1000)
                  "
                  @click="enterpriseClick(scope.row.id)"
                >
                  参加招聘会
                </el-button>
              </template>
            </el-table-column> -->
          <el-table-column label="招聘会状态" width="width" align="center">
            <template slot-scope="scope">
              <el-tag
                :type="
                  new Date() > new Date(scope.row.signEndTime * 1000)
                    ? 'info'
                    : 'success'
                "
              >
                {{
                  new Date() > new Date(scope.row.signEndTime * 1000)
                    ? "已结束"
                    : "进行中"
                }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="prop" label="操作" width="230">
            <template slot-scope="scope">
              <el-button
                v-if="
                  scope.row.companyStatus === 0 &&
                  new Date() < new Date(scope.row.signEndTime * 1000)
                "
                type="primary"
                size="small"
                @click="cJEnterpriseClick(scope.row.id)"
                >参加招聘会</el-button
              >
              <el-button
                v-if="
                  scope.row.companyStatus === 1 &&
                  new Date() < new Date(scope.row.signEndTime * 1000)
                "
                type="success"
                size="small"
                @click="addEnterpriseClick(scope.row.id)"
                >新增职位</el-button
              >
              <el-button
                v-if="
                  scope.row.companyStatus === 1 &&
                  new Date() < new Date(scope.row.signEndTime * 1000)
                "
                type="warning"
                size="small"
                @click="editEnterpriseClick(scope.row.id)"
                >修改职位</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="10" style="margin-top: 20px" type="flex" justify="end">
          <!-- <el-col :span="6">
            <el-button type="primary" size="small" @click="exportExcelClick"
              >导出Excel</el-button
            >
          </el-col> -->
          <!-- <el-col :span="6">
              <el-button
                type="primary"
                size="small"
                @click="addPositionClick"
                :disabled="!selectedJobFair"
              >新增</el-button>
              <el-button 
                type="primary" 
                size="small"
                :disabled="!selectedJobFair"
              >修改</el-button>
            </el-col> -->
          <el-col :span="6">
            <el-pagination
              background
              @size-change="handleSizeAllChange"
              @current-change="handleCurrentAllChange"
              :current-page="selJobFairQuery.page"
              :page-size="selJobFairQuery.pagesize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="allTotal"
            >
            </el-pagination>
          </el-col>
        </el-row>
      </el-tab-pane>
      <!-- <el-tab-pane label="已报名" name="2">
          <el-table :data="selJobFairRegList" style="width: 100%">
            <el-table-column prop="prop" label="招聘会内容" width="width">
              <template slot-scope="scope">
                <h3>{{ scope.row.title }}</h3>
                <div>
                  举办时间：{{ scope.row.holdStartTime | dateFormat }} 至
                  {{ scope.row.holdEndTime | dateFormat }}
                </div>
                <div>
                  参会企业{{ scope.row.totalCompany }} 参会个人{{
                    scope.row.totalPersonal
                  }}
                  浏览次数 {{ scope.row.click }}
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="type" label="类型">
              <template slot-scope="scope">
                <div>{{ scope.row.type === 1 ? "线上" : "线下" }}</div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="350" align="center">
              <template slot-scope="scope">
                <div class="operation-btns">
                  <div class="btn-wrapper">
                  </div>
                  <div class="tag-wrapper">
                    <el-tag
                      :type="
                        new Date() > new Date(scope.row.signStartTime * 1000)
                          ? 'info'
                          : 'success'
                      "
                    >
                      {{
                        new Date() > new Date(scope.row.signStartTime * 1000)
                          ? "已结束"
                          : "进行中"
                      }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-row
            :gutter="10"
            style="margin-top: 20px"
            type="flex"
            justify="end"
          >
            <el-pagination
              background
              @size-change="handleSizeRegChange"
              @current-change="handleCurrentRegChange"
              :current-page="selJobFairQuery.page"
              :page-size="selJobFairQuery.pagesize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="signUpTotal"
            >
            </el-pagination>
          </el-row>
        </el-tab-pane> -->
    </el-tabs>
    <!-- </el-card> -->

    <!-- 新增职位 -->
    <el-dialog title="新增职位" :visible.sync="addPositionDialog" width="width">
      <div>
        <el-table
          ref="multipleTable"
          :data="selPositionLists"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="jobname" label="职位名称" width="width">
          </el-table-column>
          <el-table-column
            prop="address"
            label="地址"
            width="width"
            align="center"
          >
          </el-table-column>

          <el-table-column
            prop="platform"
            label="平台"
            width="width"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="addtime"
            label="添加时间"
            width="width"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.addtime | dateFormat }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改职位 -->
    <el-dialog
      title="修改职位"
      :visible.sync="editPositionDialog"
      width="width"
    >
      <div>
        <el-table
          ref="editMultipleTable"
          :data="selPositionLists"
          style="width: 100%"
          @selection-change="handleEditSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="jobname" label="职位名称" width="width">
          </el-table-column>

          <el-table-column
            prop="address"
            label="地址"
            width="width"
            align="center"
          >
          </el-table-column>

          <el-table-column
            prop="platform"
            label="薪资区间"
            width="width"
            align="center"
          >
            <template slot-scope="scope">
              <div>{{ scope.row.minWage }} - {{ scope.row.maxWage }}</div>
            </template>
          </el-table-column>

          <el-table-column
            prop="addtime"
            label="添加时间"
            width="width"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.addtime | dateFormat }}
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <el-button @click="handleEditCancel">取 消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 参会职位 -->
    <el-dialog
      title="参会职位"
      :visible.sync="attendPositionDialog"
      width="width"
    >
      <div>
        <el-table :data="attendPositionLists" style="width: 100%">
          <el-table-column align="center" prop="prop" label="label">
          </el-table-column>
          <el-table-column align="center" prop="prop" label="label">
          </el-table-column>
          <el-table-column align="center" prop="prop" label="label">
          </el-table-column>
          <el-table-column align="center" prop="prop" label="label">
          </el-table-column>
          <el-table-column align="center" prop="prop" label="label">
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  selJobFairListApi,
  jobFairAddCompanyApi,
  selJobFairByJidAndUidApi,
  addJobFairJobApi,
  selPositionListApi,
  updateJobFairJobByUidApi,
  selJobFairJobByUidApi,
  exportExcelApi,
} from "@/api/jobFair";
import { mapGetters } from "vuex";
import { EventBus } from "@/event-bus";
export default {
  data() {
    return {
      activeName: "1",
      // 请求参数
      selJobFairQuery: {
        page: 1,
        pagesize: 10,
        uid: "",
        // uid: "",
        // type: 1,
        type: null,
      },
      // 全部
      selJobFairLists: [],
      // 已报名
      selJobFairRegList: [],
      allTotal: 0,
      signUpTotal: 0,
      // 企业参加招聘会
      jobFairAddCompanyQuery: {
        jobfairId: "",
        uid: "",
        utype: 1,
      },
      // 招聘会下职位
      addJobFairJobQuery: {
        jobIds: [],
        jobfairId: "",
        uid: "",
        utype: 1,
      },

      // 修改职位
      editJobFairJobQuery: {
        jobIds: [],
        jobfairId: "",
        uid: "",
        utype: 1,
      },
      id: "",
      // 根据uid查询招聘会企业参会职位
      selJobFairJobQuery: {
        uid: "",
        jobFairId: "",
      },

      // 企业发布职位列表
      selPositionLists: [],
      editJobFairPositionLists: [],
      addPositionDialog: false,
      selectedJobFair: null,
      editPositionDialog: false,
    };
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    this.selJobFairQuery.uid = this.userId;
    this.addJobFairJobQuery.uid = this.userId;
    this.selJobFairJobQuery.uid = this.userId;
    this.editJobFairJobQuery.uid = this.userId;
    this.selJobFairList();
    this.selPositionList();
  },
  methods: {
    // 修改职位确认
    async handleEditConfirm() {
      try {
        const res = await updateJobFairJobByUidApi(this.editJobFairJobQuery);
        if (res.code === 1) {
          this.$message.success("修改职位成功");
          this.selJobFairList();
          this.editPositionDialog = false;
        } else {
          this.$message.error("修改职位失败");
        }
      } catch {
        this.$message.error("修改职位失败");
      }
    },
    // 新增职位
    addEnterpriseClick(id) {
      this.$router.push({
        name: "postPosition",
        query: {
          source: 0,
          id: id,
        },
      });
    },
    // 导出Excel
    async exportExcelClick() {
      if (!this.id) {
        this.$message.warning("请先选择一个招聘会");
        return;
      }
      let loading = null;
      try {
        await this.$confirm(
          "此操作将导出招聘会下所有企业和职位, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        // 显示loading
        loading = this.$loading({
          lock: true,
          text: "正在导出数据,请稍候...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)",
        });

        const res = await exportExcelApi(this.id);

        if (res.code === 1 && res.data) {
          // 创建a标签下载
          const link = document.createElement("a");
          link.href = res.data;
          link.download = "招聘会下企业和岗位信息导出.xlsx";
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          this.$message.success("导出成功");
        } else {
          this.$message.error("导出失败");
        }
      } catch (error) {
        console.error("导出错误:", error);
        this.$message.error("导出失败");
      } finally {
        // 关闭loading
        if (loading) {
          loading.close();
        }
      }
    },
    // 修改职位
    async editEnterpriseClick(id) {
      this.selJobFairJobQuery.jobFairId = id;
      this.editJobFairJobQuery.jobfairId = id;
      try {
        const res = await selJobFairJobByUidApi(this.selJobFairJobQuery);
        this.editJobFairPositionLists = res.data;

        this.editJobFairJobQuery.jobIds = this.editJobFairPositionLists.map(
          (item) => item.id
        );
        console.log(this.editJobFairJobQuery.jobIds);

        // 打开对话框
        this.editPositionDialog = true;

        // 等待对话框中的表格渲染完成
        this.$nextTick(() => {
          if (
            this.editJobFairPositionLists &&
            this.editJobFairPositionLists.length > 0
          ) {
            this.editJobFairPositionLists.forEach((editItem) => {
              const matchingPosition = this.selPositionLists.find(
                (item) => item.id === editItem.id
              );
              if (matchingPosition) {
                this.$refs.editMultipleTable.toggleRowSelection(
                  matchingPosition,
                  true
                );
              }
            });
          }
        });
      } catch (error) {
        this.$message.error("获取职位信息失败");
      }
    },
    // 修改职位取消
    handleEditCancel() {
      this.editPositionDialog = false;
      this.editJobFairJobQuery.jobIds = [];
      this.editJobFairJobQuery.jobfairId = "";
    },
    // 参加招聘会
    cJEnterpriseClick(id) {
      this.addJobFairJobQuery.jobfairId = id;
      this.addPositionDialog = true;
    },
    // 处理选择变化
    handleSelectionJobFireChange(selection) {
      if (selection.length > 1) {
        // 清除之前的选择
        this.$refs.jobFairTable.clearSelection();
        // 只保留最新选择的行
        const lastSelected = selection[selection.length - 1];
        this.$refs.jobFairTable.toggleRowSelection(lastSelected, true);
        // 更新 id 和选中项
        console.log(lastSelected);

        this.id = lastSelected.id;
        this.selectedJobFair = lastSelected;
      } else {
        // 只有一个选择时直接更新
        this.id = selection[0]?.id || "";
        this.selectedJobFair = selection[0] || null;
      }
    },

    // 处理职位选择变化
    handleSelectionChange(selection) {
      console.log(selection);
      // 更新 jobIds 数组
      this.addJobFairJobQuery.jobIds = selection.map((item) => item.id);
      console.log("Selected job IDs:", this.addJobFairJobQuery.jobIds);
    },
    // 修改职位职位选择变化
    handleEditSelectionChange(selection) {
      // 更新 editJobFairJobQuery 中的 jobIds
      this.editJobFairJobQuery.jobIds = selection.map((item) => item.id);
      // 同时更新 selJobFairJobQuery 中的 jobIds
      // this.selJobFairJobQuery.jobIds = selection.map((item) => item.id);
      console.log(this.editJobFairJobQuery);
      console.log("Selected job IDs:", this.editJobFairJobQuery.jobIds);
    },

    // 取消按钮处理
    handleCancel() {
      // 清空选择和 jobIds
      this.$refs.multipleTable.clearSelection();
      this.addJobFairJobQuery.jobIds = [];
      this.addPositionDialog = false;
    },

    // 确认按钮处理
    async handleConfirm() {
      // if (this.addJobFairJobQuery.jobIds.length === 0) {
      //   this.$message.warning('请选择至少一个职位');
      //   return;
      // }
      // 这里可以添加提交逻辑
      console.log("Submitting:", this.addJobFairJobQuery);
      const res = await addJobFairJobApi(this.addJobFairJobQuery);
      console.log(res);
      if (res.code === 1) {
        this.$message.success("新增职位成功");
        // this.$router.push({
        //   name:'postPosition',
        //   query: {
        //     source:0
        //   }
        // })
        this.selJobFairList();
        this.addPositionDialog = false;
        this.addJobFairJobQuery.jobIds = [];
        this.addJobFairJobQuery.jobfairId = "";
      } else {
        this.$message.error("新增失败");
      }
    },

    // 打开弹窗时重置选择
    addPositionClick() {
      if (!this.selectedJobFair) {
        this.$message.warning("请先选择一个招聘会");
        return;
      }

      // 确保 jobfairId 已设置
      if (!this.addJobFairJobQuery.jobfairId) {
        this.addJobFairJobQuery.jobfairId = this.selectedJobFair.id;
      }

      // 清空之前的选择
      this.addJobFairJobQuery.jobIds = [];
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }

      // 打开弹窗
      this.addPositionDialog = true;
      console.log("Current jobfairId:", this.addJobFairJobQuery.jobfairId);
    },

    // 关闭弹窗时的处理
    handleDialogClose() {
      this.$refs.multipleTable.clearSelection();
      this.addJobFairJobQuery.jobIds = [];
    },

    // 当前企业发布职位列表查询
    async selPositionList() {
      const res = await selPositionListApi(this.userId);
      console.log(res);
      this.selPositionLists = res.data;
    },
    // 已报名点击分页
    handleSizeRegChange(e) {
      this.selJobFairQuery.pagesize = e;
      this.selJobFairList();
    },
    // 已报名点击分页
    handleCurrentRegChange(e) {
      this.selJobFairQuery.page = e;
      this.selJobFairList();
    },
    // 全部点击分页
    handleSizeAllChange(e) {
      this.selJobFairQuery.pagesize = e;
      this.selJobFairList();
    },
    // 全部点击分页
    handleCurrentAllChange(e) {
      this.selJobFairQuery.page = e;
      this.selJobFairList();
    },
    // 列表渲染
    async selJobFairList() {
      try {
        const res = await selJobFairListApi(this.selJobFairQuery);
        this.selJobFairLists = res.records;
        this.allTotal = res.total;
        // 清除之前的选择
        // this.clearSelection();
      } catch (error) {
        // console.error("获取招聘会列表失败:", error);
        // this.$message.error("获取列表失败");
      }
    },
    // 点击tab
    async handleClick(tab, event) {
      console.log(tab, event);
      if (tab.name === "2") {
        this.selJobFairQuery.type = 1;
        const res = await selJobFairListApi(this.selJobFairQuery);
        this.selJobFairRegList = res.records;
        this.signUpTotal = res.total;
      }
    },
    // 检查行是否可选
    checkSelectable(row) {
      return row.companyStatus == 1; // 只有已报名的可以选择
    },
  },
};
</script>

<style lang="scss" scoped>
.operation-btns {
  transform: translateX(-130px);
  display: grid;
  grid-template-columns: auto 60px; /* 第二列固定宽度 */
  align-items: center;
  gap: 8px;

  .btn-wrapper {
    text-align: right;

    // .join-btn {
    //   margin: 0;
    //   padding: 5px 12px;
    //   height: 24px;
    //   line-height: 1;
    // }
  }

  .tag-wrapper {
    width: 60px; /* 固定标签容器宽度 */

    .el-tag {
      margin: 0;
      width: 100%; /* 标签占满容器宽度 */
    }
  }
}

/* 隐藏已上传文件的 picture-card 样式 */
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    border: none;
    background: none;

    &:hover {
      .el-upload-list__item-actions {
        opacity: 1;
      }
    }
  }

  .el-upload-list__item-actions {
    background: rgba(0, 0, 0, 0.5);

    .el-upload-list__item-delete {
      color: #fff;
    }
  }
}

/* 隐藏上传按钮 */
.hide-upload {
  :deep(.el-upload--picture-card) {
    display: none !important;
  }
}

/* 确保预览图片正常显示 */
:deep(.el-upload-list--picture-card .el-upload-list__item-thumbnail) {
  object-fit: cover;
  width: 100%;
  height: 100%;
}

/* 调整预览图片容器的样式 */
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
  margin: 0 8px 8px 0;
}
</style>
